package com.lin.reggie.service.Impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lin.reggie.entity.Category;
import com.lin.reggie.entity.Page;
import com.lin.reggie.exception.BusinessException;
import com.lin.reggie.mapper.CategoryMapper;
import com.lin.reggie.mapper.DishMapper;
import com.lin.reggie.mapper.SetMealMapper;
import com.lin.reggie.service.CateoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CateoryServiceImpl implements CateoryService {

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    //保存菜品分类
    @Override
    public void save(Category category) {
        //补全参数
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.save(category);
    }



    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize){
        //设置页面大小
        PageHelper.startPage(page,pageSize);
        //2.查询数据出来
        List<Category> categoryList = categoryMapper.findAll();
        //3.把集合封装到Pageinfo对象
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        //把pageinfo的数据封装到page对象中
        Page<Category> PageResult = new Page<>(pageInfo.getList(), pageInfo.getTotal(), pageSize, page);
        return PageResult;
    }

    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetMealMapper setMealMapper;
    @Override
    public void removeById(Long id) {
        Integer count = dishMapper.findByCid(id);
        if (count>=1){
            throw new BusinessException("该类别关联了菜品无法删除");
            //异常类的作用：通知你当前程序出现何种类型问题，一类名有见名般异常知意的意思。
            // NullPointerException  WifiException
        }
        Integer count2 = setMealMapper.findByCid(id);
        if (count2>=1){
            throw new BusinessException("该类别关联了套餐无法删除");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void update(Category category) {
        //先查询用户输入的类名在数据库里存不存在，如果存在，那就返回提示已存在不让修改
        Integer count = categoryMapper.selectByNameCount(category);
        //判断是否大于0
        if (count>0){
            throw new BusinessException("该用户名已经存在,修改失败");
        }
        //设置修改时间
        category.setUpdateTime(LocalDateTime.now());
        //访问业务层修改数据
        categoryMapper.update(category);
    }
    /**
     * 查询所有分类数据
     * @return List
     */
    public List<Category> findAll(){
        return categoryMapper.findAll();
    }

    /**
     * 根据type查询分类列表数据
     *
     * @param type
     * @return list
     */
    @Override
    public List<Category> findAllByType(Integer type) {

        List<Category> allByType = categoryMapper.findAllByType(type);
        return allByType;
    }
}
